<?php
	/*
	 *	Copyright 2007 John Oren
	 *
	 *	Licensed under the Apache License, Version 2.0 (the "License");
	 *	you may not use this file except in compliance with the License.
	 *	You may obtain a copy of the License at
	 *		http://www.apache.org/licenses/LICENSE-2.0
	 *	Unless required by applicable law or agreed to in writing, software
	 *	distributed under the License is distributed on an "AS IS" BASIS,
	 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 *	See the License for the specific language governing permissions and
	 *	limitations under the License.
	 */


	/**
	 * Manages processing and display for lists based on a row's database information.
	 *
	 * @author John Oren
	 * @version 1.1 July 31, 2008
	 */
	class ListManager {
		/** ARRAY - Array of filters to apply to the database list. */
		protected $filters;
		/** STRING - name of the database column to use in a SQL ORDER BY clause to apply to the database list. */
		protected $order;
        /** STRING - The direction (asc/desc) to sort by. */
        protected $sortDir;
        /** BOOLEAN - True if this list should display in a fullscreen table. */
        protected $fullScreen;

		/**
		 * Constructs a new list (does not initiate any display or processing).
		 *
		 * @param $fullScreen BOOLEAN - True if the list should be in a fullscreen table.
		 */
		function __construct($fullScreen=true) {
			$this->filters = array();
			$this->order = null;
            $this->sortDir = "asc";
            $this->fullScreen = $fullScreen;
		}

		/**
		 * Adds a filter to the list being displayed.
		 *
		 * @param $filter Filter - The filter object to add.
		 * @return VOID
		 */
		function addFilter(Filter $filter) {
			$this->filters[] = $filter;
        }

		/**
		 * Generates and displays a list (HTML table) of data using the given row as a template.
		 *
		 * @param $fieldset Fieldset - fieldset to use as a template for fields and field titles.
         * @param $keyField Field - The primary key field for the provided fieldset.
		 * @param $linkField Field - The database field to use as a link to allow for editing/deleting a particular field.
		 * @param $QS STRING - Any text to apply to the end of links. An '&' is prepended to this if it is not empty.
		 * @param $data ARRAY Form data from filter forms.
		 * @return VOID
		 */
		function display(Fieldset $fieldset, Field $keyField, Field $linkField, $QS, $data=null) {
			if(!empty($QS)) {
				$QS = "&".$QS;
			}

			$fields = $fieldset->getFields();
			print $this->generateFilterForms($this->filters, $data);

			$where = Filter::getFilterClause($this->filters);
			if(!empty($this->order)) {
				$order = "ORDER BY `".$this->order."` ".$this->sortDir;
			}

            $result = DatabaseManager::checkError("select * from `".$fieldset->getTableName()."` ".$where." ".$order);

			print '<table id="sortable-table-0" class="sortable';
            if($this->fullScreen) {
                print ' full';
            }
            print '">';
			//add list headers
            print '<thead>';
			print '<tr>';
			foreach($fields as $field) {
				if($field->isInList()) {
					print '<th class="sortcol">'.$field->getTitle(true).'</th>';
				}
			}
			print '</tr>';
            print '</thead>';

            print '<tbody>';
			//add list data
			while($entry = DatabaseManager::fetchAssoc($result)) {
				print "<tr>";
				foreach($fields as $field) {
					if(!$field->isInList()) {
						continue;
					}
					print "<td>";
					$val = $field->getListView($entry[$field->getName()]);
					if($field->getFieldName() == $linkField->getFieldName()) {
						print '<a href="?id='.$entry[$keyField->getName()].$QS.'">'.$val.'</a>';
					} else {
						print $val;
					}
					print "</td>";
				}
				print "</tr>";
			}
            print '</tbody>';
			print '</table>';
		}

        /**
		 * Generates forms from any filters that may be applied to this form.
		 *
		 * @param $filters ARRAY - Array of filters to generate forms for.
		 * @param $data ARRAY - Form data to use to populate filter data.
		 * @return STRING HTML form to use for filtering the list.
		 */
		protected function generateFilterForms($filters, $data) {
			if(count($filters) == 0) {
				return "";
			}
			$ret = '<form method="post" action="">';

			foreach($filters as $filter) {
				$filter->setDefaultValue(array_shift($data));
				$ret .= $filter->getForm()."<br>";
			}

			$ret .= '<input type="submit" name="filter" value="Apply Filter';
			if(count($this->filters) > 1) {
				$ret .= 's';
			}
			$ret .= '">';
			$ret .= '</form>';

			return $ret;
		}

		/**
		 * Sets the MySQL ORDER BY clause (The phrase "ORDER BY" is automatically included).
		 *
		 * @param $order STRING - Name of the column to order the display by.
		 * @param $ascending BOOLEAN - Sorts ascending if true
		 * @return VOID
		 */
		function setOrderBy($order, $ascending=true) {
			$this->order = $order;
            $this->sortAscending($ascending);
        }

        /**
         * Changes the sort order of results
         *
         * @param $yes BOOLEAN - Sorts ascending if true
         * @return VOID
         */
        function sortAscending($yes) {
            if($yes) {
                $this->sortDir = "asc";
            } else {
                $this->sortDir = "desc";
            }
        }
	}
?>
